<template>
	<div>
		<a-form ref="formRef" :model="formModel" :rules="formRules" layout="vertical">
			<a-card title="工作经历" class="form-card">
				<div v-for="(work, index) in formData.workExperiences" :key="index" class="work-item">
					<a-row :gutter="16">
						<a-col :span="24">
							<a-form-item
								:label="index === 0 ? '公司名称' : ''"
								:name="['workExperiences', index, 'company']"
								:rules="[{ required: true, message: '请输入公司名称' }]"
							>
								<a-input v-model:value="work.company" placeholder="请输入公司名称" />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="16">
						<a-col :span="24">
							<a-form-item
								:label="index === 0 ? '职位' : ''"
								:name="['workExperiences', index, 'position']"
								:rules="[{ required: true, message: '请输入职位' }]"
							>
								<a-input v-model:value="work.position" placeholder="请输入职位" />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item
								:label="index === 0 ? '开始日期' : ''"
								:name="['workExperiences', index, 'startDate']"
								:rules="[{ required: true, message: '请选择开始日期' }]"
							>
								<a-date-picker
									v-model:value="work.startDate"
									placeholder="请选择开始日期"
									style="width: 100%"
									picker="month"
									valueFormat="YYYY-MM"
								/>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item
								:label="index === 0 ? '结束日期' : ''"
								:name="['workExperiences', index, 'endDate']"
								:rules="[{ required: true, message: '请选择结束日期' }]"
							>
								<a-date-picker
									v-model:value="work.endDate"
									placeholder="请选择结束日期"
									style="width: 100%"
									picker="month"
									valueFormat="YYYY-MM"
								/>
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="16">
						<a-col :span="24">
							<a-form-item
								:label="index === 0 ? '离职原因' : ''"
								:name="['workExperiences', index, 'reasonForLeaving']"
							>
								<a-textarea v-model:value="work.reasonForLeaving" :rows="3" placeholder="请输入离职原因" />
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="16">
						<a-col :span="24">
							<a-form-item :label="index === 0 ? '证明人联系方式' : ''" :name="['workExperiences', index, 'reference']">
								<a-input v-model:value="work.reference" placeholder="请输入证明人联系方式" />
							</a-form-item>
						</a-col>
					</a-row>
					<div v-if="formData.workExperiences.length > 1" class="remove-button">
						<a-button type="link" @click="removeWorkExperience(index)">删除</a-button>
					</div>
				</div>
				<a-button type="dashed" block @click="addWorkExperience">
					<PlusOutlined />
					添加工作经历
				</a-button>
			</a-card>
		</a-form>
	</div>
</template>

<script setup>
	import { defineProps, reactive, ref, watch } from 'vue'
	import { message } from 'ant-design-vue'
	import { PlusOutlined } from '@ant-design/icons-vue'
	import dayjs from 'dayjs'
	import onboardingRegistryApi from '@/api/hrms/onboarding/registry/onboardingRegistryApi'

	const props = defineProps({
		modelValue: {
			type: Object,
			default: () => ({})
		}
	})

	const formRef = ref()

	// 表单数据模型
	const formModel = ref({
		workExperiences: []
	})

	// 表单数据
	const formData = reactive({
		workExperiences: []
	})

	// 表单验证规则
	const formRules = {}

	// 监听父组件传递的数据变化
	watch(
		() => props.modelValue,
		(newVal) => {
			if (newVal) {
				// 解析工作经历数据，从 workExperience 字段获取
				if (Array.isArray(newVal.workExperience)) {
					// 处理日期格式转换
					const workExperiences = [...newVal.workExperience]
					workExperiences.forEach((work) => {
						if (work.startDate && typeof work.startDate === 'string') {
							work.startDate = dayjs(work.startDate)
						}
						if (work.endDate && typeof work.endDate === 'string') {
							work.endDate = dayjs(work.endDate)
						}
					})
					formData.workExperiences = workExperiences
					formModel.value.workExperiences = workExperiences // 同步更新表单模型
				} else {
					// 确保至少有一条工作经历
					const defaultWork = {
						company: undefined,
						position: undefined,
						startDate: undefined,
						endDate: undefined,
						reasonForLeaving: undefined,
						reference: undefined
					}
					formData.workExperiences = [defaultWork]
					formModel.value.workExperiences = [defaultWork]
				}
			}
		},
		{ immediate: true, deep: true }
	)

	// 添加工作经历
	const addWorkExperience = () => {
		const newWork = {
			company: undefined,
			position: undefined,
			startDate: undefined,
			endDate: undefined,
			reasonForLeaving: undefined,
			reference: undefined
		}
		formData.workExperiences.push(newWork)
		formModel.value.workExperiences.push(newWork) // 同步更新表单模型
	}

	// 删除工作经历
	const removeWorkExperience = (index) => {
		if (formData.workExperiences.length > 1) {
			formData.workExperiences.splice(index, 1)
			formModel.value.workExperiences.splice(index, 1) // 同步更新表单模型
		} else {
			message.warning('至少保留一条工作经历信息')
		}
	}

	// 保存数据方法（供父组件调用）
	async function saveData() {
		try {
			await formRef.value.validateFields()
			const submitData = formData.workExperiences.map((work) => {
				const workCopy = { ...work }
				// 将dayjs对象转换为字符串格式 (年月格式)
				if (workCopy.startDate && dayjs.isDayjs(workCopy.startDate)) {
					workCopy.startDate = workCopy.startDate.format('YYYY-MM')
				}
				if (workCopy.endDate && dayjs.isDayjs(workCopy.endDate)) {
					workCopy.endDate = workCopy.endDate.format('YYYY-MM')
				}
				return workCopy
			})
			const requestData = new FormData()
			requestData.append(
				'onboardingRegistryEditBo',
				new Blob([JSON.stringify({ workExperienceEditBoList: submitData })], {
					type: 'application/json'
				})
			)
			await onboardingRegistryApi.updateRegistryInfo(props.modelValue.id, requestData)
			message.success('工作经历保存成功')
			return true
		} catch (error) {
			// 更详细地处理验证错误
			if (error.errorFields) {
				// 表单验证错误
				const firstError = error.errorFields[0]
				const fieldName = firstError.name.join('.')
				message.error(`表单填写有误: ${firstError.errors[0]} (${fieldName})`)
			} else {
				// 其他错误（如网络错误、服务器错误等）
				console.error('保存数据失败:', error)
				message.error('保存失败，请稍后重试')
			}
			return false
		}
	}

	// 暴露保存数据方法给父组件调用
	defineExpose({
		saveData
	})
</script>

<style scoped>
	.form-card {
		margin-bottom: 16px;
		border-radius: 8px;
	}

	.form-card :deep(.ant-card-head) {
		background-color: #fafafa;
		border-radius: 8px 8px 0 0;
	}

	.work-item {
		position: relative;
		padding: 16px;
		border: 1px solid #f0f0f0;
		border-radius: 8px;
		margin-bottom: 16px;
	}

	.remove-button {
		text-align: right;
	}
</style>
